package com.yjz.springdatajpa.controller;

import com.yjz.springdatajpa.dto.ServerResult;
import com.yjz.springdatajpa.entity.User;
import com.yjz.springdatajpa.repository.UserRepository;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author :yuanJinZhong
 * @description:
 * @date :2019/3/25-22:30
 */
@RequestMapping("/api")
@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    /**
     * 添加用户
     * @param user 用户信息
     * @return 添加成功后的用户id
     */
    @PostMapping("/users")
    public ServerResult saveUser(@RequestBody User user){
        User saveUser = userRepository.save(user);
        return new ServerResult("添加成功",saveUser.getId());
    }

    /**
     * 更新用户信息
     * @param user 用户信息
     * @param id 用户id
     * @return 更新结果
     */
    @PutMapping("/users/{id}")
    public ServerResult updateUserById(@RequestBody User user,@PathVariable Long id){
        user.setId(id);
        userRepository.save(user);
        return new ServerResult("修改成功",id);
    }

    /**
     * 获取用户信息
     * @param id 用户id
     * @return 用户信息
     */
    @GetMapping("/users/{id}")
    public ServerResult findUserById(@PathVariable Long id){
       Optional<User>  user = userRepository.findById(id);
        return new ServerResult("查找成功",user.get());
    }

    /**
     * 删除用户信息
     * @param id 用户id
     * @return 删除结果
     */
    @DeleteMapping("/users/{id}")
    public ServerResult deleteUserById(@PathVariable Long id){
        userRepository.deleteById(id);
        return new ServerResult("删除成功",null);
    }

}